package com.endava.dao.impl;

import com.endava.dao.BookDAO;
import com.endava.model.Book;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BookDAOImpl implements BookDAO {
	
	private Connection connection;
	private static final String INSERT_STATEMENT = "INSERT INTO book(name, author, releaseDate) values (?, ?, ?)";
	private static final String DELETE_STATEMENT = "DELETE FROM book WHERE id=?";
	private static final String UPDATE_STATEMENT = "UPDATE book SET name = ? AND author = ? AND releaseDate = ? WHERE id = ? ";
	private static final String GET_BY_ID_STATEMENT = "SELECT * FROM book WHERE id = ?";

	public void create(Book book) {
		try {
			PreparedStatement statement = connection
					.prepareStatement(INSERT_STATEMENT);
			statement.setString(1, book.getName());
			statement.setString(2, book.getAuthor());
			statement.setString(3, book.getReleaseDate());
			statement.executeUpdate();
			System.out.println("Book successfully saved...");
		} catch (SQLException e) {
			System.out.println("Exception: " + e.getMessage());
		}
	}

	public void update(Book book) {
		try {
			PreparedStatement statement = connection
					.prepareStatement(UPDATE_STATEMENT);
			statement.setString(1, book.getName());
			statement.setString(2, book.getAuthor());
			statement.setString(3, book.getReleaseDate());
			statement.setInt(4, book.getId());
			statement.executeUpdate();
			System.out.println("Book successfully updated...");
		} catch (SQLException e) {
			System.out.println("Exception: " + e.getMessage());
		}
	}

	public void delete(int id) {
		try {
			PreparedStatement statement = connection
					.prepareStatement(DELETE_STATEMENT);
			statement.setInt(1, id);
			statement.executeUpdate();
			System.out.println("Book successfully deleted...");
		} catch (SQLException e) {
			System.out.println("Exception: " + e.getMessage());
		}
	}

	public Book getBookById(int id) {
		PreparedStatement statement;
		ResultSet result = null;
		Book book = null;
		try {
			statement = connection.prepareStatement(GET_BY_ID_STATEMENT);
			statement.setInt(1, id);
			result = statement.executeQuery();
			book = new Book(result.getInt(1), result.getString(2),
					result.getString(3), result.getString(4));
		} catch (SQLException e) {
			System.out.println("Exception: " + e.getMessage());
		}

		return book;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}
}
